<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 200px">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 角色表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="角色编号" prop="roleId" width="120" />
        <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" />
        <el-table-column label="显示顺序" prop="roleSort" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button 
                  type="warning" 
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleDataScope" icon="CircleCheck">数据权限</el-dropdown-item>
                    <el-dropdown-item command="handleAuthUser" icon="User">分配用户</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <span>
              <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="1">正常</el-radio>
            <el-radio value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuRef"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 分配数据权限对话框 -->
    <el-dialog :title="`分配数据权限: ${currentRole.roleName || ''}`" v-model="dataScopeOpen" width="500px" append-to-body>
      <el-form :model="dataScopeForm" label-width="80px">
        <el-form-item label="数据范围">
          <el-select v-model="dataScopeForm.dataScope" placeholder="请选择数据范围" style="width: 100%">
            <el-option label="全部数据权限" value="1" />
            <el-option label="自定义数据权限" value="2" />
            <el-option label="本部门数据权限" value="3" />
            <el-option label="本部门及以下数据权限" value="4" />
            <el-option label="仅本人数据权限" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="dataScopeForm.dataScope === '2'" label="部门列表">
          <el-tree
            ref="deptTreeRef"
            :data="deptOptions"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍候"
            :props="{ label: 'name', children: 'children' }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 分配用户角色对话框 -->
    <el-dialog :title="`${currentRole.roleName || ''}: 分配用户`" v-model="authUserOpen" width="800px" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="已分配用户" name="assigned">
          <el-form :model="userQueryParams" ref="userQueryRef" :inline="true" label-width="68px">
            <el-form-item label="用户名称" prop="username">
              <el-input
                v-model="userQueryParams.username"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleUserQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="userQueryParams.phone"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter="handleUserQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleUserQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetUserQuery">重置</el-button>
            </el-form-item>
          </el-form>
          
          <el-row style="margin-bottom: 10px;">
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="Delete"
                :disabled="userIds.length === 0"
                @click="handleCancelAuthAll"
                class="table-operation-button is-danger"
              >批量取消授权</el-button>
            </el-col>
          </el-row>
          
          <el-table :data="userList" @selection-change="handleUserSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户名称" prop="username" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" prop="nickname" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" prop="phone" width="120" />
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button
                  type="danger"
                  icon="Delete"
                  class="table-operation-button is-danger"
                  size="small"
                  @click="cancelAuthUser(scope.row)"
                >解除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            v-show="totalUser > 0"
            :total="totalUser"
            v-model:page="userQueryParams.pageNum"
            v-model:limit="userQueryParams.pageSize"
            @pagination="getUserList('assigned')"
          />
        </el-tab-pane>
        <el-tab-pane label="未分配用户" name="unassigned">
          <el-form :model="userUnallocatedQueryParams" ref="userUnallocatedQueryRef" :inline="true" label-width="68px">
            <el-form-item label="用户名称" prop="username">
              <el-input
                v-model="userUnallocatedQueryParams.username"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleUnallocatedUserQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="userUnallocatedQueryParams.phone"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter="handleUnallocatedUserQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleUnallocatedUserQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetUnallocatedUserQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="Plus"
                :disabled="userSelectedIds.length === 0"
                @click="handleSelectAuthUser"
                class="table-operation-button is-primary"
              >批量授权</el-button>
            </el-col>
          </el-row>
          <el-table :data="unallocatedUserList" @selection-change="handleUnallocatedUserSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户名称" prop="username" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" prop="nickname" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" prop="phone" width="120" />
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="Plus"
                  class="table-operation-button is-primary"
                  size="small"
                  @click="handleSelectAuthUser(scope.row)"
                >授权</el-button>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            v-show="unallocatedTotalUser > 0"
            :total="unallocatedTotalUser"
            v-model:page="userUnallocatedQueryParams.pageNum"
            v-model:limit="userUnallocatedQueryParams.pageSize"
            @pagination="getUserList('unassigned')"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRolePage, addRole, updateRole, deleteRole, getRolePermissions, updateRoleStatus,
  setDataScope, getRoleUserList, getUnallocatedUserList, authUserSelectAll,
  authUserCancel, authUserCancelAll, assignPermissions, getRoleDetail, deleteBatchRole
} from '@/api/role'
import { getPermissionTree } from '@/api/permission'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const roleList = ref([])
const title = ref('')
const open = ref(false)
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuOptions = ref([])
const queryFormRef = ref()
const roleFormRef = ref()
const menuRef = ref()

// 数据权限相关
const deptTreeRef = ref()
const dataScopeOpen = ref(false)
const deptOptions = ref([])
const currentRole = ref({})

// 用户权限分配相关
const userQueryRef = ref()
const userUnallocatedQueryRef = ref()
const authUserOpen = ref(false)
const activeName = ref("assigned")
const userIds = ref([])
const userSelectedIds = ref([])
const userList = ref([])
const unallocatedUserList = ref([])
const totalUser = ref(0)
const unallocatedTotalUser = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: undefined,
  roleKey: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: '1',
  menuIds: [],
  menuCheckStrictly: true,
  remark: undefined
})

// 表单校验规则
const rules = reactive({
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
  roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
})

// 数据权限表单数据
const dataScopeForm = reactive({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  dataScope: "1",
  deptIds: []
})

// 已分配用户查询参数
const userQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  username: undefined,
  phone: undefined
})

// 未分配用户查询参数
const userUnallocatedQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  username: undefined,
  phone: undefined
})

// 获取角色列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getRolePage(queryParams)
    if (response.code === 200) {
      roleList.value = (response.data.records || []).map(role => ({
        ...role,
        status: role.status?.toString() || '0',
        roleId: role.id || role.roleId
      }))
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.roleId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 记录上一次状态切换时间，防止自动触发
const lastStatusChangeTime = ref(0)
// 记录组件是否已初始化完成
const isInitialized = ref(false)

// 角色状态修改
const handleStatusChange = async (row, newVal) => {
  // 如果组件还未初始化完成，跳过处理
  if (!isInitialized.value) {
    return
  }
  
  // 检查是否是短时间内重复触发
  const now = Date.now()
  if (now - lastStatusChangeTime.value < 300) {
    return
  }
  lastStatusChangeTime.value = now
  
  const text = row.status === '1' ? '启用' : '停用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用状态更新API
    const result = await updateRoleStatus({ 
      id: row.roleId || row.id, 
      status: parseInt(row.status) // 确保传递的是数字类型
    })
    
    if (result.code === 200) {
      ElMessage.success(text + '成功')
    } else {
      // 操作失败，恢复状态
      row.status = row.status === '1' ? '0' : '1'
      ElMessage.error(result.message || '状态修改失败')
    }
  } catch (error) {
    // 取消操作或出错，恢复为原来的状态
    row.status = row.status === '1' ? '0' : '1'
    console.error('状态修改失败:', error)
  }
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  getMenuTreeselect()
  open.value = true
  title.value = '添加角色'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  reset()
  const roleId = row.roleId || row.id || ids.value[0]
  
  // 加载权限树
  await getMenuTreeselect()
  
  // 获取角色详情
  try {
    const roleResult = await getRoleDetail(roleId)
    if (roleResult.code === 200) {
      Object.assign(form, roleResult.data)
      form.roleId = roleId
    }
    
    // 获取已分配权限
    const permResponse = await getRolePermissions(roleId)
    if (permResponse.code === 200 && permResponse.data.length > 0) {
      // 设置已选中的权限
      menuRef.value?.setCheckedKeys(permResponse.data)
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
  
  open.value = true
  title.value = '修改角色'
}

// 删除按钮操作
const handleDelete = (row) => {
  const roleIds = row.roleId || row.id ? [row.roleId || row.id] : ids.value
  if (!roleIds || roleIds.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  
  ElMessageBox.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      if (roleIds.length === 1) {
        // 单个删除
        await deleteRole(roleIds[0])
      } else {
        // 批量删除
        await deleteBatchRole(roleIds)
      }
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleDataScope':
      handleDataScope(row)
      break
    case 'handleAuthUser':
      handleAuthUser(row)
      break
    default:
      break
  }
}

// 分配数据权限操作
const handleDataScope = (row) => {
  currentRole.value = row
  dataScopeOpen.value = true
  dataScopeForm.roleId = row.roleId || row.id
  dataScopeForm.roleName = row.roleName
  dataScopeForm.roleKey = row.roleKey
  dataScopeForm.dataScope = row.dataScope || "1"
  // 这里可以调用后端API获取部门列表
  // 由于暂无部门相关API，先设置模拟数据
  deptOptions.value = [
    { 
      id: 1, 
      name: '总公司',
      children: [
        { id: 2, name: '研发部门' },
        { id: 3, name: '市场部门' },
        { id: 4, name: '财务部门' }
      ]
    }
  ]
}

// 取消数据权限
const cancelDataScope = () => {
  dataScopeOpen.value = false
}

// 提交数据权限
const submitDataScope = async () => {
  if (dataScopeForm.dataScope === "2" && !deptTreeRef.value) {
    ElMessage.warning("请选择部门")
    return
  }
  
  try {
    const deptIds = dataScopeForm.dataScope === "2" 
      ? deptTreeRef.value.getCheckedKeys() 
      : []
    
    await setDataScope({
      roleId: dataScopeForm.roleId,
      dataScope: dataScopeForm.dataScope,
      deptIds: deptIds
    })
    
    ElMessage.success("数据权限设置成功")
    dataScopeOpen.value = false
  } catch (error) {
    console.error('设置数据权限失败:', error)
    ElMessage.error('设置数据权限失败')
  }
}

// 分配用户操作
const handleAuthUser = (row) => {
  currentRole.value = row
  authUserOpen.value = true
  userQueryParams.roleId = row.roleId || row.id
  userUnallocatedQueryParams.roleId = row.roleId || row.id
  activeName.value = "assigned"
  getUserList("assigned")
}

// 获取角色用户列表
const getUserList = async (type) => {
  const params = type === "assigned" ? userQueryParams : userUnallocatedQueryParams
  try {
    const response = await (type === "assigned" 
      ? getRoleUserList(params) 
      : getUnallocatedUserList(params))
    
    if (response.code === 200) {
      if (type === "assigned") {
        userList.value = response.data.records || []
        totalUser.value = response.data.total
      } else {
        unallocatedUserList.value = response.data.records || []
        unallocatedTotalUser.value = response.data.total
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 已分配用户搜索
const handleUserQuery = () => {
  userQueryParams.pageNum = 1
  getUserList("assigned")
}

// 已分配用户搜索重置
const resetUserQuery = () => {
  userQueryRef.value?.resetFields()
  handleUserQuery()
}

// 未分配用户搜索
const handleUnallocatedUserQuery = () => {
  userUnallocatedQueryParams.pageNum = 1
  getUserList("unassigned")
}

// 未分配用户搜索重置
const resetUnallocatedUserQuery = () => {
  userUnallocatedQueryRef.value?.resetFields()
  handleUnallocatedUserQuery()
}

// 已分配用户多选框选中数据
const handleUserSelectionChange = (selection) => {
  userIds.value = selection.map(item => item.id || item.userId)
}

// 未分配用户多选框选中数据
const handleUnallocatedUserSelectionChange = (selection) => {
  userSelectedIds.value = selection.map(item => item.id || item.userId)
}

// 选择授权用户
const handleSelectAuthUser = async (row) => {
  const roleId = currentRole.value.roleId || currentRole.value.id
  const userIdList = row && row.id ? [row.id] : userSelectedIds.value
  
  if (!userIdList || userIdList.length === 0) {
    ElMessage.warning('请选择需要授权的用户')
    return
  }
  
  try {
    await authUserSelectAll({ 
      roleId: roleId, 
      userIds: userIdList.join(',')
    })
    ElMessage.success('授权成功')
    activeName.value = 'assigned'
    getUserList('assigned')
    getUserList('unassigned')
  } catch (error) {
    console.error('授权失败:', error)
    ElMessage.error('授权失败')
  }
}

// 取消用户授权
const cancelAuthUser = async (row) => {
  const roleId = currentRole.value.roleId || currentRole.value.id
  try {
    await authUserCancel({ 
      roleId: roleId,
      userId: row.id || row.userId
    })
    ElMessage.success('取消授权成功')
    getUserList('assigned')
    getUserList('unassigned')
  } catch (error) {
    console.error('取消授权失败:', error)
    ElMessage.error('取消授权失败')
  }
}

// 查询菜单树结构
const getMenuTreeselect = async () => {
  try {
    const response = await getPermissionTree()
    if (response.code === 200) {
      menuOptions.value = formatPermissions(response.data)
    } else {
      ElMessage.error(response.message || '获取权限树失败')
    }
  } catch (error) {
    console.error('获取权限树失败:', error)
    ElMessage.error('获取权限树失败')
  }
}

// 格式化权限数据为树形结构
const formatPermissions = (permissions) => {
  if (!permissions || permissions.length === 0) return []
  
  return permissions.map(item => ({
    id: item.id,
    label: item.permissionName,
    children: formatPermissions(item.children)
  }))
}

// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value, type) => {
  if (type === 'menu') {
    const treeList = menuOptions.value
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
  }
}

// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value, type) => {
  if (type === 'menu') {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
  }
}

// 树权限（父子联动）
const handleCheckedTreeConnect = (value, type) => {
  if (type === 'menu') {
    form.menuCheckStrictly = value
  }
}

// 表单重置
const reset = () => {
  if (menuRef.value !== undefined) {
    menuRef.value.setCheckedKeys([])
  }
  Object.assign(form, {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: '1',
    menuIds: [],
    menuCheckStrictly: true,
    remark: undefined
  })
  roleFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交表单
const submitForm = () => {
  roleFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 获取选中的菜单权限ID
        const menuKeys = menuRef.value?.getCheckedKeys() || []
        const halfMenuKeys = menuRef.value?.getHalfCheckedKeys() || []
        form.menuIds = [...menuKeys, ...halfMenuKeys] // 合并全选和半选的菜单ID
        
        if (form.roleId) {
          await updateRole(form)
          // 分配菜单权限
          if (form.menuIds.length > 0) {
            await assignPermissions({
              roleId: form.roleId,
              permissionIds: form.menuIds
            })
          }
          ElMessage.success('修改成功')
        } else {
          const result = await addRole(form)
          if (result.code === 200 && form.menuIds.length > 0) {
            // 分配菜单权限
            await assignPermissions({
              roleId: result.data.id || result.data.roleId,
              permissionIds: form.menuIds
            })
          }
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 批量取消用户授权
const handleCancelAuthAll = async () => {
  if (userIds.value.length === 0) {
    ElMessage.warning('请选择需要取消授权的用户')
    return
  }
  
  const roleId = currentRole.value.roleId || currentRole.value.id
  try {
    await ElMessageBox.confirm(`确认要批量取消${userIds.value.length}个用户的角色授权吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await authUserCancelAll({
      roleId: roleId,
      userIds: userIds.value.join(',')
    })
    
    ElMessage.success('取消授权成功')
    getUserList('assigned')
    getUserList('unassigned')
  } catch (error) {
    console.error('批量取消授权失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getList()
  // 设置组件初始化完成标志
  setTimeout(() => {
    isInitialized.value = true
  }, 500)
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #ffffff none;
  border-radius: 4px;
  width: 100%;
}
</style>
